Please read these documents from these websites:
Capitalization Styles
c = camel Case
P = Pascal Case
_ = Prefix with _Underscore
Identifier Public Protected Internal Private Notes Project File P Match Assembly & Namespace. Source File P Match contained class. Other Files P Apply where possible. Namespace P Partial Project/Assembly match. Class or Structure P P P P Add suffix of subclass. Interface P P P P Prefix with a capital . Generic Class P P P P Use or as Type identifier. Method / Function P P P P Use a Verb or Verb-Object pair. Property P P P P Do not prefix with or . Field P P P _c Only use Private fields. No Hungarian Notation! Constant P P P _c Static Field P P P _c Only use Private fields. Enumeration P P P P Options are also Pascal Case. Delegate P P P P Event P P P P Variable P c c Inline Variable c Avoid single-character and enumerated names. Parameter c
- Abbreviation - the shortened form of a word.
- Initialism - Abbreviation from the first (or first few) letters of several words which forms a non-pronounceable word and each letter must be spelled separately. For example: HTML.
- Acronym - A word formed from the first (or first few) letters of several words which forms a pronounceable word. For Example: FLAP.
- Contraction - A word, formed by reducing, omitting or combining some of the words of a longer phrase.
To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of abbreviations:
- Do not use abbreviations or contractions as parts of identifier names. For example, use GetWindow instead of GetWin.
- Do not use acronyms that are not generally accepted in the computing field.
- Where appropriate, use well-known acronyms to replace lengthy phrase names. For example, use UI for User Interface and OLAP for On-line Analytical Processing.
- Use Pascal or Camel Case for acronyms more than two characters long. For example, use HtmlButton, htmlButton or UserGuid.
- However, you can capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io.
- Pascal Casing is recommended when the term is part of a multi-word member. For example: IoException instead of IOException.
- Do not use abbreviations in identifiers or parameter names. If you must use abbreviations, use camel case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word.
Notes about ID vs. Id
- ID - acronym from "Identifying Document". Use if you want refer for some paper or plastic document.
- Id - abbreviation from "Identity", "Identification". Use if you want refer to some identification number of object.
Notes about "Direcotry" and "Folder"
- Directory – It is a container for files and other directories. Directory has permanent physical location on the hard drive or other storage medium.
- Folder – It is an interface and container for a collection of objects. Folder can be stored on disk, in memory by a DLL, in the Registry and may contain items that are not true files but are virtual objects. These are folders: "My Computer", "Control Panel", "Dial-Up Networking", "Network Neighbourhood", "Printers", "Fonts" and the "Recycle Bin"
- In Windows all directories are folders but not all folders are directories.
- "Folders" includes everything that we used to call a "directory" plus some abstract objects.
Better to use this :
System.IO.DirectoryInfo[] directories;
directories = new System.IO.Directory.GetDirectories("C:\\");
System.IO.DirectoryInfo directory = directories[0];
Than this :
System.IO.DirectoryInfo[] folders;
Links
- http://www.acronymattic.com/ - Searching over 3 million acronyms, abbreviations, and initialisms.
- All indentation should be done with Tab characters (\0x09). Tab size should be set to 4 spaces. Tab (not space) is the only way to go! - because different programmers can see code as they prefer and everybody is happy.
- Use braces, even for wrapping single statements. This makes updating the code easier in the future.
for (int i = 0; i < 100; i++){ DoSomething(i); }
;- All methods should use XML doc comments. For internal dev comments, the <devdoc> tag should be used:
/// <summary>Public stuff about the method</summary>
/// <param name="bar">What a neat parameter!</param>
/// <devdoc who="John Smith">Cool internal stuff!</devdoc>
public void MyMethod(int bar) { … }
- Write internal comments as normal sentences. End them with dot:
Right: // Open new window here.
Wrong: // Open new window here
- Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:
Do use a single space after a comma between function arguments.
Right: Console.In.Read(myChar, 0, 1);
Wrong: Console.In.Read(myChar,0,1);
Do not use a space after the parenthesis and function arguments.
Right: CreateFoo(myChar, 0, 1);
Wrong: CreateFoo( myChar, 0, 1 ) ;
Do not use spaces between a function name and parenthesis.
Right: CreateFoo();
Wrong: CreateFoo ();
Do not use spaces inside brackets.
Right: x = dataArray[index];
Wrong: x = dataArray[ index ];
Do use a single space before flow control statements.
Right: while (x == y);
Wrong: while(x==y);
Do use a single space before and after comparison operators.
Right: if (x == y);
Wrong: if (x==y);
Do use a single space after and before braces.
Right: if (x != y){ x = y };
Wrong: if (x != y){x = y};
Do use a single space after and before alternative separator (catch/else).
Right: if (x != y){ x = y } else { x = 0 }
Wrong: if (x != y){ x = y }else{ x = 0 }
Note: Shorter format: x = (x != y) ? y : 0;
ALWAYS! declare variables of loops or you are looking into big problem if you run two different loops with same variable names asynchronously at same time!:
Right: for (var i; i < 10; i++){...
Wrong: for (i; i < 10; i++){...
Right: for (var property in someObject){...
Wrong: for (property in someObject){...
- Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use "this." in C# and "Me." in VB.NET.
- If you need to comment if...then statements then use if...then inside comment sentence as well:
-- If emoplyee identification was not specified then...
if (EmoplyeeGUID){
// Do some action here.
DoSomething();
}
File Organization
Source files should contain only one public type, although multiple internal classes are allowed. Source files should be given the name of the public class in the file. Directory names should follow the namespace for the class. For example, I would expect to find the public class “System.Windows.Forms.Control” in “System\Windows\Forms\Control.cs”…
Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types). Using statements should be inside the namespace declaration.
namespace MyNamespace
{
using System;
public class MyClass : IFoo
{
// Fields.
int foo;
// Constructors.
public MyClass() { … }
// Properties.
public int Foo { get { … } set { … } }
// Events.
public event EventHandler FooChanged { add { … } remove { … } }
// Methods.
void DoSomething() { … }
void FindSomethind() { … }
// Private interface implementations.
void IFoo.DoSomething() { DoSomething(); }
// Nested types.
class NestedType { … }
}
}
Rules, that doesn't correspond with the Microsoft rules:
For JavaScript use same coding standard as for C#.
Best coding practice is:
"Turn on XML documentation" and "Format things the way Visual Studio (2005) does".
Group similar functions into classes
Use inheritance.
Avoid to use Response.Write() or alert() inside the functions because in this case code will be usable only on server or client side. You can:
Generate string inside function and return it.
Or Create Message.Write(text) function. Detect
if script is running on server side or client side Inside this function and
show message accordingly.
this.IsServerSide = false;
if (typeof(Response)
== "object") this.IsServerSide =
true
;
// If we are on server side
then...
if (this.IsServerSide){
// Write
text to output.
Response.Write(text);
}else{
// Show
popup message.
alert(text);
}
// Create array with some Data.
var array = new Array();
array.push("one");
array.push("two");
// Create class.
var class1 = new Class1();
// Bind function to event.
class1.OnDataBound = function(sender, e){ alert("Data DataSource["+e.Data+"] was binded to "+sender.Type); };
// Set data source.
class1.DataSource = array;
// Bind Data.
class1.DataBind();
---------------------------------------------------------------
System.EventArgs = function(name){
this.Name = "";
this.Type = "System.EventArgs";
//---------------------------------------------------------
// METHOD: ToString
//---------------------------------------------------------
this.ToString = function(){
var results = new String();
for (var property in this){
var skip = false;
skip = skip || (property == "InitializeClass");
skip = skip || (property == "ToString");
if (!skip) results += property+"='"+this[property]+"';";
}
results = "e["+results+"]";
return results;
}
// Optional: this allows automatic conversation of this object to string by JavaSript.
// this.toString = this.ToString;
//---------------------------------------------------------
// INIT: InitializeClass
//---------------------------------------------------------
this.InitializeClass = function(){
this.Name = name ? name : new String;
}
this.InitializeClass();
}
Namespace1.Namespace2.Class1 = function(id,target,value){
this.Type = "Namespace1.Namespace2.Class1";
//---------------------------------------------------------
// PROPERTIES: Public
//---------------------------------------------------------
this.id = new String;
this.Target = null;
this.DataSource = null
this.Node = null;
//---------------------------------------------------------
// PROPERTIES: Private
//---------------------------------------------------------
// This property is required.
var me = this;
//---------------------------------------------------------
// HANDLERS / PUBLIC EVENTS:
//---------------------------------------------------------
// Function which runs external function if it was attached.
this.RiseEvent = function(e){ if (this[e.Name]){ this[e.Name](this,e) } }
//---------------------------------------------------------
// Assign 'null' to event handlers.
this.OnInit = null;
this.OnDataBound = null
this.OnClick = null;
//---------------------------------------------------------
// METHOD: DataBind
//---------------------------------------------------------
this.DataBind = function(){
// Bind array to Node.
var text = new String;
for (var i = 0; i < this.DataSource.length; i++){
text += this.DataSource[i]+",";
}
this.Node.innerHTML = "Data: "+text+" - Click Here.";
var e = new System.EventArgs("OnDataBound");
// Always: set parameter first time with quotes.
// Get parameter value with e.Data reference.
e["Data"] = this.DataSource;
this.RiseEvent(e);
}
//---------------------------------------------------------
// EVENT PRIVATE: onClick
//---------------------------------------------------------
this.onClick = function(sender, e){
sender.Node.innerHTML = "Clicked! Wait...";
// Display content of node after 1 second.
// We need to use 'me' otherwise we will loose reference to object.
setTimeout(function(){ me.Node.innerHTML += "Done."; },1000);
}
//---------------------------------------------------------
// INIT: InitializeInterface
//---------------------------------------------------------
this.InitializeInterface = function(sender, e){
this.Node = this.Target.createElement("div");
this.Node.style.position = "absolute";
this.Node.style.top = "10px";
this.Node.style.left = "10px";
this.Node.style.cursor = "pointer";
this.Node.style.padding = "8px";
this.Node.style.border = "solid 1px #000000";
this.Node.style.backgroundColor = "#d0ffd0";
this.Node.innerHTML = "no data";
this.Target.body.appendChild(this.Node);
}
//---------------------------------------------------------
// INIT: InitializeEvents
//---------------------------------------------------------
this.InitializeEvents = function(sender, e){
this.Node.onclick = function(){ me.onClick(me, new System.EventArgs("OnClick")) };
}
//---------------------------------------------------------
// INIT: InitializeClass
//---------------------------------------------------------
this.InitializeClass = function(){
// By default use current document.
this.Target = target ? target : document;
// Set submited values or default values.
this.id = id ? id : "";
// Create HTML Element.
this.InitializeInterface(this);
// Attach events.;
this.InitializeEvents(this);
// Rise init event.
this.RiseEvent(new System.EventArgs("OnInit"));
}
this.InitializeClass.apply(this,arguments);
}
Using:
var MyObject = null;
Group1.Init = function(){
MyObject = new Namespace1.Namespace2.Class1("testId");
// Attach function to event. Replace "On" with "_";
MyObject.OnDataBound = Group1.MyObject_DataBound;
} Group1.MyObject_OnDataBound
= function(sender, e){ // Do some stuff here then data is bounded. } Notes:
var properties = new String;
for(property in ToArrayBox){
properties += typeof(ToArrayBox[property])+" "+property+"; isNull="+((ToArrayBox[property]) ? false : true)+"\r\n";
}
alert(properties);
Naming
Use C# coding standards for JavaScript
Coding Practice
Useful Links
Event compatibility tables information for cross Browser development:
http://www.quirksmode.org/js/events_compinfo.html
Type Conversions:
http://www.jibbering.com/faq/faq_notes/type_convert.html
Arrays
The conventional way of coding a for loop to process an array lis like this:
for (var i = 0; i < myArray.length; i++) {...
The problem with this is that evaluation of the length of the array using myArray.length has to be performed every time around the loop. These two methods are about 50% faster (because we are creating variable that holds that value):
var j = myArray.length;
for (var i = 0; i < j; i++) {...
or reverse:
for (var i =
myArray.length-1; i > -1; i--) {...
Note: this can be replace by this:
var i = myArray.length; while(i--){...